﻿/*---------------------------------------------------------
 * Author : Tharinduni Udugamasuriya
 * Date : June 2014
 * MasterToolBar : MasterToolBar User Control's Code Behind
 ---------------------------------------------------------*/

using CrystalDecisions.CrystalReports.Engine;
using DSPL.Common.Classes;
using DSPL.Common.ViewModel;
using DSPL.Contracts;
using DSPL.Contracts.Common;
using DSPL.Contracts.Interfaces;
using DSPL.Reports.Classes;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Linq;


namespace DSPL.Common
{
    /// <summary>
    /// Interaction logic for MasterToolBar.xaml
    /// </summary>
    public partial class MasterToolBar : UserControl
    {
        public MasterToolBar()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this))
                return;

            ResolveDependancies();
        }

        public void ResolveDependancies()
        {
            IUnityContainer container = GlobalVariables.GlobalUnityContainer;
            if (container != null)
            {
                MasterReadService = container.Resolve<IReadService>();
                MasterWriteService = container.Resolve<IWriteService>();
                ColumnWithValue = container.Resolve<IColumnWithValue>();
                CommonValidations = container.Resolve<ICommonValidations>();
                MessageService = container.Resolve<IMessageService>();
            }
        }

        #region Declaring User Control Internal/Private/Protected Variables

        private string firstFocusElement;
        private int currentIndex;
        DataRow NewDataRow;
        DataRow OldDataRow;
        string oldFilePath;
        private string uniqueKey;
        private bool isSaveEnable;
        private int primaryKey;
        private string primaryKeyField = string.Empty;
        private string filterString = string.Empty;
        private string sortString = string.Empty;
        private string title = string.Empty;
        private string reportName = string.Empty;
        private string imageFileName;

        #endregion

        #region Declaring Dependency Properties

        #region Visibility of Buttons

        public static readonly DependencyProperty NewVisibilityProperty = DependencyProperty.Register("NewVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty EditVisibilityProperty = DependencyProperty.Register("EditVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty DeleteVisibilityProperty = DependencyProperty.Register("DeleteVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty UndoVisibilityProperty = DependencyProperty.Register("UndoVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty FirstVisibilityProperty = DependencyProperty.Register("FirstVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty PreviousVisibilityProperty = DependencyProperty.Register("PreviousVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty NextVisibilityProperty = DependencyProperty.Register("NextVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty LastVisibilityProperty = DependencyProperty.Register("LastVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty PrintVisibilityProperty = DependencyProperty.Register("PrintVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty ListVisibilityProperty = DependencyProperty.Register("ListVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty SearchVisibilityProperty = DependencyProperty.Register("SearchVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty FilterVisibilityProperty = DependencyProperty.Register("FilterVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty SortVisibilityProperty = DependencyProperty.Register("SortVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty SaveVisibilityProperty = DependencyProperty.Register("SaveVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty CloseVisibilityProperty = DependencyProperty.Register("CloseVisibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty Button1VisibilityProperty = DependencyProperty.Register("Button1Visibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty Button2VisibilityProperty = DependencyProperty.Register("Button2Visibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty Button3VisibilityProperty = DependencyProperty.Register("Button3Visibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty Button4VisibilityProperty = DependencyProperty.Register("Button4Visibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty Button5VisibilityProperty = DependencyProperty.Register("Button5Visibility", typeof(Visibility), typeof(MasterToolBar), new PropertyMetadata(Visibility.Visible));

        #endregion

        public static readonly DependencyProperty TableNameProperty = DependencyProperty.Register("TableName", typeof(string), typeof(MasterToolBar), new PropertyMetadata("abc"), new ValidateValueCallback(TableNameValidateCallBack));

        public static readonly DependencyProperty LogTableNameProperty = DependencyProperty.Register("LogTableName", typeof(string), typeof(MasterToolBar), new PropertyMetadata("abc"));

        public static readonly DependencyProperty CurrentRowProperty = DependencyProperty.Register("CurrentRow", typeof(DataRow), typeof(MasterToolBar), new PropertyMetadata(null, OnCurrentRowChanged));

        public static readonly DependencyProperty SqlTranProperty = DependencyProperty.Register("SqlTran", typeof(SqlTransaction), typeof(MasterToolBar), new PropertyMetadata(null));

        public static readonly DependencyProperty IsValidProperty = DependencyProperty.Register("IsValid", typeof(bool), typeof(MasterToolBar), new PropertyMetadata(true));

        public static readonly DependencyProperty FormModeProperty = DependencyProperty.Register("FormMode", typeof(Modes), typeof(MasterToolBar), new PropertyMetadata(Modes.Undo, FormModeChangedCallBack));

        public static readonly DependencyProperty IgnoreTableListProperty = DependencyProperty.Register("IgnoreTableList", typeof(string), typeof(MasterToolBar), new PropertyMetadata(""));

        public static readonly DependencyProperty ReportFolderProperty = DependencyProperty.Register("ReportFolder", typeof(string), typeof(MasterToolBar), new PropertyMetadata(""));

        public static readonly DependencyProperty ImageFilePathProperty = DependencyProperty.Register("ImageFilePath", typeof(string), typeof(MasterToolBar), new PropertyMetadata(""));

        #region Methods Execute Type

        public static readonly DependencyProperty IsDataValidateExecuteProperty = DependencyProperty.Register("IsDataValidateExecute", typeof(bool), typeof(MasterToolBar), new PropertyMetadata(true));

        public static readonly DependencyProperty IsDataUpdValidateExecuteProperty = DependencyProperty.Register("IsDatUpdaValidateExecute", typeof(bool), typeof(MasterToolBar), new PropertyMetadata(true));

        public static readonly DependencyProperty IsDataDelValidateExecuteProperty = DependencyProperty.Register("IsDataDelValidateExecute", typeof(bool), typeof(MasterToolBar), new PropertyMetadata(true));

        public static readonly DependencyProperty IsDataSaveProperty = DependencyProperty.Register("IsDataSave", typeof(bool), typeof(MasterToolBar), new PropertyMetadata(true));

        public static readonly DependencyProperty IsDataUpdateProperty = DependencyProperty.Register("IsDataUpdate", typeof(bool), typeof(MasterToolBar), new PropertyMetadata(true));

        public static readonly DependencyProperty IsDataDeleteProperty = DependencyProperty.Register("IsDataDelete", typeof(bool), typeof(MasterToolBar), new PropertyMetadata(true));

        public static readonly DependencyProperty IsImageSaveProperty = DependencyProperty.Register("IsImageSave", typeof(bool), typeof(MasterToolBar), new PropertyMetadata(false));

        public static readonly DependencyProperty IsResetDefaultExecuteProperty = DependencyProperty.Register("IsResetDefaultExecute", typeof(bool), typeof(TransactionToolBar), new PropertyMetadata(true));
        
        #endregion

        #endregion

        #region Declaring Properties

        public IReadService MasterReadService { get; set; }
        public IWriteService MasterWriteService { get; set; }
        public IColumnWithValue ColumnWithValue { get; set; }
        public ICommonValidations CommonValidations { get; set; }
        public IMessageService MessageService { get; set; }

        #region Visibility of Buttons

        public Visibility NewVisibility
        {
            get { return (Visibility)GetValue(NewVisibilityProperty); }
            set { SetValue(NewVisibilityProperty, value); }
        }

        public Visibility EditVisibility
        {
            get { return (Visibility)GetValue(EditVisibilityProperty); }
            set { SetValue(EditVisibilityProperty, value); }
        }

        public Visibility DeleteVisibility
        {
            get { return (Visibility)GetValue(DeleteVisibilityProperty); }
            set { SetValue(DeleteVisibilityProperty, value); }
        }

        public Visibility UndoVisibility
        {
            get { return (Visibility)GetValue(UndoVisibilityProperty); }
            set { SetValue(UndoVisibilityProperty, value); }
        }

        public Visibility FirstVisibility
        {
            get { return (Visibility)GetValue(FirstVisibilityProperty); }
            set { SetValue(FirstVisibilityProperty, value); }
        }

        public Visibility PreviousVisibility
        {
            get { return (Visibility)GetValue(PreviousVisibilityProperty); }
            set { SetValue(PreviousVisibilityProperty, value); }
        }

        public Visibility NextVisibility
        {
            get { return (Visibility)GetValue(NextVisibilityProperty); }
            set { SetValue(NextVisibilityProperty, value); }
        }

        public Visibility LastVisibility
        {
            get { return (Visibility)GetValue(LastVisibilityProperty); }
            set { SetValue(LastVisibilityProperty, value); }
        }

        public Visibility PrintVisibility
        {
            get { return (Visibility)GetValue(PrintVisibilityProperty); }
            set { SetValue(PrintVisibilityProperty, value); }
        }

        public Visibility ListVisibility
        {
            get { return (Visibility)GetValue(ListVisibilityProperty); }
            set { SetValue(ListVisibilityProperty, value); }
        }

        public Visibility SearchVisibility
        {
            get { return (Visibility)GetValue(SearchVisibilityProperty); }
            set { SetValue(SearchVisibilityProperty, value); }
        }

        public Visibility FilterVisibility
        {
            get { return (Visibility)GetValue(FilterVisibilityProperty); }
            set { SetValue(FilterVisibilityProperty, value); }
        }

        public Visibility SortVisibility
        {
            get { return (Visibility)GetValue(SortVisibilityProperty); }
            set { SetValue(SortVisibilityProperty, value); }
        }

        public Visibility SaveVisibility
        {
            get { return (Visibility)GetValue(SaveVisibilityProperty); }
            set { SetValue(SaveVisibilityProperty, value); }
        }

        public Visibility CloseVisibility
        {
            get { return (Visibility)GetValue(CloseVisibilityProperty); }
            set { SetValue(CloseVisibilityProperty, value); }
        }

        public Visibility Button1Visibility
        {
            get { return (Visibility)GetValue(Button1VisibilityProperty); }
            set { SetValue(Button1VisibilityProperty, value); }
        }

        public Visibility Button2Visibility
        {
            get { return (Visibility)GetValue(Button2VisibilityProperty); }
            set { SetValue(Button2VisibilityProperty, value); }
        }

        public Visibility Button3Visibility
        {
            get { return (Visibility)GetValue(Button3VisibilityProperty); }
            set { SetValue(Button3VisibilityProperty, value); }
        }

        public Visibility Button4Visibility
        {
            get { return (Visibility)GetValue(Button4VisibilityProperty); }
            set { SetValue(Button4VisibilityProperty, value); }
        }

        public Visibility Button5Visibility
        {
            get { return (Visibility)GetValue(Button5VisibilityProperty); }
            set { SetValue(Button5VisibilityProperty, value); }
        }

        #endregion

        #region General Properties

        public DataTable DtAllMasterDataOriginal { get; private set; }

        public DataTable DtAllMasterData { get; private set; }

        public DataTable DtLogTableData { get; private set; }

        public string TableName
        {
            get { return (string)GetValue(TableNameProperty); }
            set { SetValue(TableNameProperty, value); }
        }

        public string LogTableName
        {
            get { return (string)GetValue(LogTableNameProperty); }
            set { SetValue(LogTableNameProperty, value); }
        }

        public Modes FormMode
        {
            get { return (Modes)GetValue(FormModeProperty); }
            set
            {
                SetValue(FormModeProperty, value);
                EnableDisableButtons(FormMode);
            }
        }

        public string FirstFocusElement
        {
            get { return firstFocusElement; }
            set { firstFocusElement = value; }
        }

        public DataRow CurrentRow
        {
            get { return (DataRow)GetValue(CurrentRowProperty); }
            set { SetValue(CurrentRowProperty, value); }
        }

        public int CurrentIndex
        {
            get { return currentIndex; }
            set
            {
                currentIndex = value;
            }
        }

        public string UniqueKey
        {
            get { return uniqueKey; }
            set
            {
                uniqueKey = value;
            }
        }        

        public string PrimaryKeyField
        {
            get { return primaryKeyField; }
            set
            {

                if (value == null)
                {
                    primaryKeyField = "PK";
                }
                else
                {
                    primaryKeyField = value;
                }
            }
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }

        public string ReportFolder
        {
            get { return (string)GetValue(ReportFolderProperty); }
            set { SetValue(ReportFolderProperty, value); }
        }

        public string ReportName
        {
            get { return reportName; }
            set { reportName = value; }
        }
        public bool IsValid
        {
            get { return (bool)GetValue(IsValidProperty); }
            set { SetValue(IsValidProperty, value); }
        }

        public SqlTransaction SqlTran
        {
            get { return (SqlTransaction)GetValue(SqlTranProperty); }
            set { SetValue(SqlTranProperty, value); }
        }

        public string IgnoreTableList
        {
            get { return (string)GetValue(IgnoreTableListProperty); }
            set { SetValue(IgnoreTableListProperty, value); }
        }

        public string ImageFilePath
        {
            get { return (string)GetValue(ImageFilePathProperty); }
            set { SetValue(ImageFilePathProperty, value); }
        }

        #endregion

        #region Methods Execute Type

        public bool IsDataValidateExecute
        {
            get { return (bool)GetValue(IsDataValidateExecuteProperty); }
            set { SetValue(IsDataValidateExecuteProperty, value); }
        }

        public bool IsDataUpdValidateExecute
        {
            get { return (bool)GetValue(IsDataUpdValidateExecuteProperty); }
            set { SetValue(IsDataUpdValidateExecuteProperty, value); }
        }

        public bool IsDataDelValidateExecute
        {
            get { return (bool)GetValue(IsDataDelValidateExecuteProperty); }
            set { SetValue(IsDataDelValidateExecuteProperty, value); }
        }

        public bool IsDataSave
        {
            get { return (bool)GetValue(IsDataSaveProperty); }
            set { SetValue(IsDataSaveProperty, value); }
        }

        public bool IsDataUpdate
        {
            get { return (bool)GetValue(IsDataUpdateProperty); }
            set { SetValue(IsDataUpdateProperty, value); }
        }

        public bool IsDataDelete
        {
            get { return (bool)GetValue(IsDataDeleteProperty); }
            set { SetValue(IsDataDeleteProperty, value); }
        }

        public bool IsImageSave
        {
            get { return (bool)GetValue(IsImageSaveProperty); }
            set { SetValue(IsImageSaveProperty, value); }
        }

        public bool IsResetDefaultExecute
        {
            get { return (bool)GetValue(IsResetDefaultExecuteProperty); }
            set { SetValue(IsResetDefaultExecuteProperty, value); }
        }

        #endregion

        #endregion

        #region Exposable Event Handlers

        public event EventHandler<EventArgs> PreDataValidation;             //use to data validate before internal method execution, when data saving
        public event EventHandler<EventArgs> PostDataValidation;            //use to data validate after internal method execution, when data saving
        public event EventHandler<EventArgs> PreDataDelValidation;          //use to data validate before internal method execution, when data delete record
        public event EventHandler<EventArgs> PostDataDelValidation;         //use to data validate after internal method execution, when data delete record
        public event EventHandler<EventArgs> PreDataInsert;                 //use to data saving processes before internal method execution, when data inserting
        public event EventHandler<EventArgs> PostDataInsert;                //use to data saving processes after internal method execution, when data inserting
        public event EventHandler<EventArgs> PreDataUpdate;                 //use to data saving processes before internal method execution, when data updating
        public event EventHandler<EventArgs> PostDataUpdate;                //use to data saving processes after internal method execution, when data updating
        public event EventHandler<EventArgs> PreDataDelete;                 //use to data deletion processes before internal method execution, when data deleting
        public event EventHandler<EventArgs> PostDataDelete;                //use to data deletion processes after internal method execution, when data deleting
        public event EventHandler<EventArgs> RefreshExternalDataObjects;    //use to external data population 
        public event EventHandler<EventArgs> PostDataSaveProcess;           //use to external data population 
        public event EventHandler<EventArgs> PreResetDefault;               //use to reset form data before internal method execution
        public event EventHandler<EventArgs> PostResetDefault;              //use to reset form data after internal method execution
        
        #region Exposable Events for Additionl Buttons

        public event EventHandler<EventArgs> ExecuteButton1Event;
        public event EventHandler<EventArgs> ExecuteButton2Event;
        public event EventHandler<EventArgs> ExecuteButton3Event;
        public event EventHandler<EventArgs> ExecuteButton4Event;
        public event EventHandler<EventArgs> ExecuteButton5Event;

        #endregion

        #endregion

        #region Property Changed Callback Methods

        private static bool TableNameValidateCallBack(object _tableName)
        {
            return !_tableName.Equals("");
        }

        private static void FormModeChangedCallBack(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
            MasterToolBar objMstTool = depObj as MasterToolBar;

            if (objMstTool != null)
                objMstTool.EnableDisableButtons((Modes)e.NewValue);
        }

        private static void OnCurrentRowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MasterToolBar masterToolBar = d as MasterToolBar;

            if (masterToolBar != null)
            {
                masterToolBar.SetFileName();
                masterToolBar.SetFilePath();
                if (masterToolBar.RefreshExternalDataObjects != null)
                    masterToolBar.RefreshExternalDataObjects(masterToolBar, new EventArgs());                    
            }
        }

        #endregion

        #region Private Methods

        //Reset Image File Name when changing Current record
        private void SetFileName()
        {
            if (this.CurrentRow != null)
            {
                string[] uniqueKeys = this.uniqueKey.Split('+');

                this.imageFileName = string.Empty;

                foreach (string uniqKey in uniqueKeys)
                {
                    this.imageFileName += this.CurrentRow[uniqKey].ToString();
                }
            }
        }

        //Reset Image File Name & Path
        private void SetFilePath()
        {
            string fileName = string.Empty;

            if (!string.IsNullOrEmpty(imageFileName))
            {
                if (!Directory.Exists(GlobalVariables.AttachmentFolderPath))
                    Directory.CreateDirectory(GlobalVariables.AttachmentFolderPath);

                IList<string> files = Directory.EnumerateFiles(GlobalVariables.AttachmentFolderPath).ToList();
                
                fileName = files.FirstOrDefault(p => Path.GetFileNameWithoutExtension(p).Equals(imageFileName));
            }

            ImageFilePath = fileName;
            oldFilePath = fileName;

        }

        //Load Master Table data from database
        private void LoadAllMasterData()
        {
            if (MasterReadService != null)
            {
                DtAllMasterDataOriginal = MasterReadService.GetAllMasterData(TableName);
                DtAllMasterData = DtAllMasterDataOriginal;
                FilteringAndSortingDatatable();
            }
        }

        //Load Master Log Table data from database
        private void LoadLogTableData()
        {
            if (MasterReadService != null)
                DtLogTableData = MasterReadService.GetDummyRecord(LogTableName);
        }

        //Change properties when form mode changing
        private void EnableDisableButtons(Modes formMode)
        {
            switch (formMode)
            {
                case Modes.New:
                    isSaveEnable = true;
                    break;
                case Modes.Edit:
                    isSaveEnable = true;
                    break;
                case Modes.Delete:
                    isSaveEnable = false;
                    break;
                case Modes.Approve:
                    isSaveEnable = true;
                    break;
                case Modes.Print:
                    isSaveEnable = false;
                    break;
                case Modes.Save:
                    break;
                case Modes.Undo:
                    break;
                case Modes.None:
                    isSaveEnable = false;
                    break;
                case Modes.View:
                    break;
                case Modes.Cancel:
                    break;
                default:
                    break;
            }
            EnableDisableButtons();
        }

        //Enable Dissable buttons due to changes of FormMode & CurrentIndex
        private void EnableDisableButtons()
        {
            btnNew.IsEnabled = (!isSaveEnable);
            btnEdit.IsEnabled = (!isSaveEnable);
            btnDelete.IsEnabled = (!isSaveEnable);
            btnUndo.IsEnabled = (isSaveEnable);
            btnFirst.IsEnabled = (!isSaveEnable && (CurrentIndex != 0) && (DtAllMasterData.Rows.Count > 0));
            btnPrevious.IsEnabled = (!isSaveEnable && (CurrentIndex != 0) && (DtAllMasterData.Rows.Count > 0));
            btnNext.IsEnabled = (!isSaveEnable && (CurrentIndex != DtAllMasterData.Rows.Count - 1) && (DtAllMasterData.Rows.Count > 0));
            btnLast.IsEnabled = (!isSaveEnable && (CurrentIndex != DtAllMasterData.Rows.Count - 1) && (DtAllMasterData.Rows.Count > 0));
            btnPrint.IsEnabled = (!isSaveEnable);
            btnFilter.IsEnabled = (!isSaveEnable);
            btnSort.IsEnabled = (!isSaveEnable);
            btnSearch.IsEnabled = (!isSaveEnable);
            btnList.IsEnabled = (!isSaveEnable);
            btnSave.IsEnabled = (isSaveEnable);
            btnClose.IsEnabled = (!isSaveEnable);
        }

        //Set the mouse pointer/cursor in to given control/element
        private void SetFirstFocusElement()
        {
            var parentWindow = Window.GetWindow(this);

            ContentControl contetn = (ContentControl)parentWindow.FindName("popupContent");

            DependencyObject contentPresenter = VisualTreeHelper.GetChild(contetn, 0);

            UserControl userControl = VisualTreeHelper.GetChild(contentPresenter, 0) as UserControl;


            var uie = (UIElement)userControl.FindName(FirstFocusElement);

            if (FormMode == Modes.New)
                uie.Focus();
            else if (FormMode == Modes.Edit)
                uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }

        //Change the CurrentRow, CurrentIndex while navigation button click
        private void SetCurrentRecord(int rowIndex)
        {
            if (DtAllMasterData != null && DtAllMasterData.Rows.Count > 0)
            {
                currentIndex = DtAllMasterData.Rows.Count <= rowIndex ? rowIndex - 1 : rowIndex;
                CurrentRow = DtAllMasterData.Rows[currentIndex];
                CurrentIndex = currentIndex;
            }
            else
                CurrentRow = DtAllMasterData.NewRow();

            EnableDisableButtons();
        }

        //Reset Data
        private void ResetDefaults(bool isLast)
        {
            if (PreResetDefault != null)
                PreResetDefault(this, new EventArgs());

            if (IsResetDefaultExecute)
            {
                LoadAllMasterData();
                LoadLogTableData();

                if (FormMode == Modes.New && IsValid)
                {
                    DataRow[] foundDatarows = DtAllMasterData.Select(primaryKeyField + " = " + primaryKey.ToString());
                    if (foundDatarows.Count() > 0)
                        CurrentIndex = DtAllMasterData.Rows.IndexOf(foundDatarows[0]);
                }
                FormMode = Modes.None;
                SetCurrentRecord(isLast ? DtAllMasterData.Rows.Count - 1 : CurrentIndex);
                SqlTran = null;
                IsValid = true;
            }

            if (PostResetDefault != null)
                PostResetDefault(this, new EventArgs());
        }

        //Handeling Key Press Events of Parent Window
        private void HandleKeyPress(object sender, KeyEventArgs e)
        {
            var parentWindow = Window.GetWindow(this);
            if (parentWindow != null)
            {
                var Uie = (UIElement)Keyboard.FocusedElement;
                if (Uie != null)
                {
                    if (e.Key == Key.Enter)
                        Uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        }

        //Data Validation while saving record
        private bool DataValidation()
        {
            if (PreDataValidation != null)
                PreDataValidation(this, new EventArgs());

            if (IsValid && IsDataValidateExecute)
            {
                if (CheckExistance())
                    ValueReplacement(Window.GetWindow(this));
                else
                    MessageService.ShowMessage(UniqueKey + " already exists. Cannot proceed.", MessageType.WarningOK);
            }
            if (PostDataValidation != null && IsValid)
                PostDataValidation(this, new EventArgs());

            return IsValid;
        }

        //Check Unique Keys are confict...
        private bool CheckExistance()
        {
            if (FormMode == Modes.New)
            {
                List<IColumnWithValue> UniqueKeyList = new List<IColumnWithValue>();
                List<Tuple<string, object, QDataType>> columnList = new List<Tuple<string, object, QDataType>>();
                columnList = GenerateUniqueColumnList();
                UniqueKeyList = ColumnWithValue.CreateIColumnWithValueList(columnList);
                string[] stringSeparators = new string[] { "+" };
                string[] nofUniqueKeys = UniqueKey.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                if (UniqueKeyList.Count == nofUniqueKeys.Length)
                    IsValid = !CommonValidations.CheckMasterRecordDuplicates(TableName, UniqueKeyList.ToArray());
            }
            return IsValid;
        }

        //Replace SQL Keywords - to avoid SQL injection
        private void ValueReplacement(Visual obj)
        {
            Visual child = (Visual)obj;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                if (child is TextBox)
                    ((TextBox)child).Text = (string)CommonValidations.ValidateSqlKeywords(((TextBox)child).Text, "TEXT");

                if (child is TextBlock)
                    ((TextBlock)child).Text = (string)CommonValidations.ValidateSqlKeywords(((TextBlock)child).Text, "TEXT");

                ValueReplacement((Visual)VisualTreeHelper.GetChild(obj, i));
            }
        }

        //Generate List with Unique Keys & thier Values
        private List<Tuple<string, object, QDataType>> GenerateUniqueColumnList()
        {
            string[] UniqueKeys = UniqueKey.Split('+');
            List<Tuple<string, object, QDataType>> columnList = new List<Tuple<string, object, QDataType>>();
            foreach (DataColumn dataCol in CurrentRow.Table.Columns)
            {
                if (UniqueKey.Contains(dataCol.ColumnName))
                    columnList.Add(new Tuple<string, object, QDataType>(dataCol.ColumnName, CurrentRow[dataCol], GetQDataType(dataCol.DataType.Name.ToUpper())));
            }
            return columnList;
        }

        //Get the QDataType as per the DataType
        private QDataType GetQDataType(string DataType)
        {
            QDataType returnValue = QDataType.TEXT;

            switch (DataType)
            {
                case "STRING":
                    returnValue = QDataType.TEXT;
                    break;

                case "DATETIME":
                    returnValue = QDataType.DATETIME;
                    break;

                case "BOOLEAN":
                    returnValue = QDataType.BOOLEAN;
                    break;

                case "INT16":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "UINT16":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "INT32":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "UINT32":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "INT64":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "UINT64":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "LONG":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "DECIMAL":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "DOUBLE":
                    returnValue = QDataType.NUMERIC;
                    break;

                case "BYTE":
                    returnValue = QDataType.BOOLEAN;
                    break;

                case "SBYTE":
                    returnValue = QDataType.BOOLEAN;
                    break;

                case "CHAR":
                    returnValue = QDataType.TEXT;
                    break;

                case "SINGLE":
                    returnValue = QDataType.NUMERIC;
                    break;

                default:
                    break;
            }

            return returnValue;
        }
        
        //Data Validation Before Delete
        private bool DataValidationToDelete()
        {
            if (PreDataDelValidation != null)
                PreDataDelValidation(this, new EventArgs());

            if (IsValid && IsDataDelValidateExecute)
                CheckValidyofDeletion();

            if (PostDataDelValidation != null && IsValid)
                PostDataDelValidation(this, new EventArgs());

            return IsValid;
        }

        //Data Validation Before Delete
        private void CheckValidyofDeletion()
        {
            int primaryKey = (int)CurrentRow[primaryKeyField];
            IsValid = CommonValidations.CheckValidyOfDeletion(TableName, primaryKey, PrimaryKeyField, IgnoreTableList);
        }

        //Insert Record
        private void InsertMasterRecord()
        {
            if (PreDataInsert != null)
                PreDataInsert(this, new EventArgs());

            if (IsValid && IsDataSave)
            {
                if (MasterReadService != null)
                {
                    var tran = SqlTran;
                    if (MasterWriteService.InsertMasterData(TableName, PrimaryKeyField, NewDataRow, ref  tran))
                    {
                        primaryKey = MasterWriteService.PrimaryKey;
                        CurrentRow[PrimaryKeyField] = primaryKey;
                        SqlTran = tran;
                        if (PostDataInsert != null && IsValid)
                            PostDataInsert(this, new EventArgs());
                    }
                    else
                    {
                        IsValid = false;
                        SqlTran = tran;
                        if (SqlTran != null)
                            SqlTran.Rollback();
                    }
                }
            }

            if (IsValid)
            {
                if (PostDataSaveProcess != null)
                {
                    PostDataSaveProcess(this, new EventArgs());
                }
                if (SqlTran != null)
                    SqlTran.Commit();
            }
            else
            {
                if (SqlTran != null && SqlTran.Connection != null)
                    SqlTran.Rollback();
            }
        }

        //Update Record
        private void UpdateMasterRecord()
        {
            if (PreDataUpdate != null)
                PreDataUpdate(this, new EventArgs());


            if (IsValid && IsDataUpdate)
            {
                if (MasterReadService != null)
                {
                    var tran = SqlTran;
                    DataRow logDataRow = DtLogTableData.NewRow();

                    foreach (DataColumn logDataRowItem in logDataRow.Table.Columns)
                    {
                        if (OldDataRow.Table.Columns.Contains(logDataRowItem.ColumnName))
                            logDataRow[logDataRowItem.ColumnName] = OldDataRow[logDataRowItem.ColumnName];
                    }

                    if (MasterWriteService.UpdateMasterData(TableName, PrimaryKeyField, LogTableName, NewDataRow, logDataRow, ref  tran))
                    {
                        SqlTran = tran;
                        if (PostDataUpdate != null && IsValid)
                            PostDataUpdate(this, new EventArgs());
                    }
                    else
                    {
                        IsValid = false;
                        SqlTran = tran;
                        if (SqlTran != null)
                            SqlTran.Rollback();
                    }
                }
            }

            if (IsValid)
            {
                if (PostDataSaveProcess != null)
                {
                    PostDataSaveProcess(this, new EventArgs());
                }
                if (SqlTran != null)
                    SqlTran.Commit();
            }
            else
            {
                if (SqlTran != null && SqlTran.Connection != null)
                    SqlTran.Rollback();
            }
        }

        //Delete Record
        private bool DeleteMasterRecord()
        {

            if (PreDataDelete != null)
                PreDataDelete(this, new EventArgs());

            if (IsValid && IsDataDelete)
            {
                if (MasterReadService != null)
                {
                    var tran = SqlTran;
                    DataRow logDataRow = DtLogTableData.NewRow();

                    foreach (DataColumn logDataRowItem in logDataRow.Table.Columns)
                    {
                        if (OldDataRow.Table.Columns.Contains(logDataRowItem.ColumnName))
                            logDataRow[logDataRowItem.ColumnName] = OldDataRow[logDataRowItem.ColumnName];
                    }

                    if (MasterWriteService.DeleteMasterData(TableName, PrimaryKeyField, LogTableName, logDataRow, ref  tran))
                    {
                        SqlTran = tran;
                        if (PostDataDelete != null && IsValid)
                            PostDataDelete(this, new EventArgs());
                    }
                    else
                    {
                        IsValid = false;
                        SqlTran = tran;
                        if (SqlTran != null)
                            SqlTran.Rollback();
                    }
                }
            }


            if (IsValid)
            {
                if (SqlTran != null)
                    SqlTran.Commit();
            }
            else
            {
                if (SqlTran != null && SqlTran.Connection != null)
                    SqlTran.Rollback();
            }

            return IsValid;
        }        

        //Select Filtered & Sorted Records set
        private void FilteringAndSortingDatatable()
        {
            if (string.IsNullOrEmpty(filterString) && string.IsNullOrEmpty(sortString))
                DtAllMasterData = DtAllMasterDataOriginal;

            else if (!string.IsNullOrEmpty(filterString))
            {
                DataRow[] drSelected;

                if (!string.IsNullOrEmpty(sortString))
                    drSelected = DtAllMasterDataOriginal.Select(filterString, sortString);
                else
                    drSelected = DtAllMasterDataOriginal.Select(filterString);

                if (drSelected.Length > 0)
                    DtAllMasterData = drSelected.CopyToDataTable();
                else
                {
                    filterString = string.Empty;
                    MessageService.ShowMessage(MessageText.FilterDataNotFound, Title, MessageType.InfoOK);
                    DtAllMasterData = DtAllMasterDataOriginal;
                }
            }
            else if (!string.IsNullOrEmpty(sortString))
            {
                DataRow[] drSelected;

                drSelected = DtAllMasterDataOriginal.Select(null, sortString);

                DtAllMasterData = drSelected.CopyToDataTable();
                //DtAllMasterData = DtAllMasterDataOriginal;
                //DtAllMasterData.DefaultView.Sort = sortString;
                //DtAllMasterData = DtAllMasterData.DefaultView.ToTable();
            }
        }

        //Common function to Save a Image to a specific folder
        private void SaveImageToFolder()
        {   
            if (!ImageFilePath.Equals(oldFilePath))
            {
                if (string.IsNullOrWhiteSpace(this.imageFileName))
                {
                    SetFileName();
                }

                if (string.IsNullOrWhiteSpace(oldFilePath))
                {
                    oldFilePath = GlobalVariables.AttachmentFolderPath + imageFileName + Path.GetExtension(ImageFilePath);
                }

                if (File.Exists(oldFilePath))
                {
                    System.IO.File.Delete(oldFilePath);
                }

                System.IO.File.Copy(ImageFilePath, oldFilePath);
            }
        }


        #endregion

        #region User Control Commands

        #region AddNew Button

        private void ExecuteAddNew(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(filterString))
            {
                MessageBoxResult isProceed;
                isProceed = MessageService.ShowMessage(MessageText.InquireProceedWithFilterExists, Title, MessageType.QuizYesNo);
                if (isProceed == MessageBoxResult.Yes)
                    filterString = "";
                else if (isProceed == MessageBoxResult.No)
                    return;
            }
            FormMode = Modes.New;
            IsValid = false;
            NewDataRow = DtAllMasterData.NewRow();
            CurrentRow = NewDataRow;
            SetFirstFocusElement();
        }

        #endregion

        #region Edit Button

        private void ExecuteEdit(object sender, RoutedEventArgs e)
        {
            if (DtAllMasterData != null && DtAllMasterData.Rows.Count > 0)
            {
                FormMode = Modes.Edit;
                IsValid = false;
                OldDataRow = DtAllMasterData.NewRow();
                foreach (DataColumn item in CurrentRow.Table.Columns)
                {
                    OldDataRow[item] = CurrentRow[item];
                }SetFirstFocusElement();
            }
            else
                MessageService.ShowMessage(MessageText.EmptyTableDeleteEditBlock, Title, MessageType.InfoOK);
        }

        #endregion

        #region Delete Button

        private void ExecuteDelete(object sender, RoutedEventArgs e)
        {
            IsValid = true;

            if (DtAllMasterData != null && DtAllMasterData.Rows.Count > 0)
            {
                FormMode = Modes.Delete;
                OldDataRow = DtAllMasterData.NewRow();
                if (DataValidationToDelete())
                {
                    MessageBoxResult isProceed;
                    isProceed = MessageService.ShowMessage(MessageText.InquireDeletion, Title, MessageType.QuizYesNo);
                    if (isProceed == MessageBoxResult.Yes)
                    {
                        OldDataRow = CurrentRow;
                        if (DeleteMasterRecord())
                            MessageService.ShowMessage(MessageText.DeletedSuccessfully, Title, MessageType.InfoOK);
                        else
                            MessageService.ShowMessage(MessageText.ErrorWhileSaving, Title, MessageType.InfoOK);

                        ResetDefaults(false);
                    }
                    
                }
                else
                    MessageService.ShowMessage(MessageText.DeleteNotAllowed, Title, MessageType.InfoOK);

            }
            else
                MessageService.ShowMessage(MessageText.EmptyTableDeleteEditBlock, Title, MessageType.InfoOK);

        }

        #endregion

        #region Undo Button

        private void ExecuteUndo(object sender, RoutedEventArgs e)
        {
            ResetDefaults(false);
        }

        #endregion

        #region Navigation Buttons

        #region Move into top record
        private void ExecuteTop(object sender, RoutedEventArgs e)
        {
            CurrentIndex = 0;
            SetCurrentRecord(CurrentIndex);
            FormMode = Modes.None;

        }
        #endregion

        #region Move into previous record
        private void ExecutePrev(object sender, RoutedEventArgs e)
        {
            if (CurrentIndex == 0)
                CurrentIndex = 0;
            else
                CurrentIndex--;
            SetCurrentRecord(CurrentIndex);
            FormMode = Modes.None;

        }
        #endregion

        #region Move into next record
        private void ExecuteNext(object sender, RoutedEventArgs e)
        {

            if (DtAllMasterData != null)
            {
                if (CurrentIndex == DtAllMasterData.Rows.Count - 1)
                    CurrentIndex = DtAllMasterData.Rows.Count - 1;
                else
                    CurrentIndex++;
                SetCurrentRecord(CurrentIndex);
                FormMode = Modes.None;

            }
        }
        #endregion

        #region Move into last record

        private void ExecuteBottom(object sender, RoutedEventArgs e)
        {

            if (DtAllMasterData != null)
                CurrentIndex = DtAllMasterData.Rows.Count - 1;
            SetCurrentRecord(CurrentIndex);
            FormMode = Modes.None;

        }

        #endregion

        #endregion

        #region Save Button

        private void ExecuteSave(object sender, RoutedEventArgs e)
        {           
            
            IsValid = true;
            if (DataValidation())
            {
                NewDataRow = CurrentRow;

                if (FormMode == Modes.New)
                    InsertMasterRecord();
                else if (FormMode == Modes.Edit)
                    UpdateMasterRecord();

                if (IsImageSave && File.Exists(ImageFilePath))
                    SaveImageToFolder();

                if (IsValid)
                {
                    MessageService.ShowMessage(MessageText.SavedSuccessfully, Title, MessageType.InfoOK);
                }
                else
                    MessageService.ShowMessage(MessageText.ErrorWhileSaving, Title, MessageType.InfoOK);

                ResetDefaults(false);
            }
        }

        #endregion

        #region Close Button

        private void ExecuteClose(object sender, RoutedEventArgs e)
        {
            Window parentwin = Window.GetWindow(this);
            if (parentwin != null)
                parentwin.Close();
        }

        #endregion

        #region List Button

        private void ExecuteList(object sender, RoutedEventArgs e)
        {
            if (DtAllMasterDataOriginal != null && DtAllMasterDataOriginal.Rows.Count > 0)
            {
                ListWindowViewModel vmListWindow = new ListWindowViewModel();
                if (vmListWindow != null)
                {
                    vmListWindow.TableName = TableName;
                    vmListWindow.FilterString = string.IsNullOrEmpty(filterString) ? "" : filterString;
                    vmListWindow.Initialize();
                    MessageService.ShowPopupWindow(vmListWindow);
                    if (vmListWindow.SelectedRow != null)
                    {
                        DtAllMasterData.PrimaryKey = new DataColumn[] { DtAllMasterData.Columns[primaryKeyField] };
                        CurrentIndex = DtAllMasterData.Rows.IndexOf(DtAllMasterData.Rows.Find(vmListWindow.SelectedRow[primaryKeyField]));
                        SetCurrentRecord(CurrentIndex);
                    }
                }
            }
        }

        #endregion

        #region Filter Button

        private void ExecuteFilter(object sender, RoutedEventArgs e)
        {
            if (DtAllMasterDataOriginal != null && DtAllMasterDataOriginal.Rows.Count > 0)
            {
                filterString = String.Empty;
                ObservableCollection<ColumnValueProperties> columnList = new ObservableCollection<ColumnValueProperties>();
                foreach (DataColumn item in DtAllMasterData.Columns)
                {
                    if (!GlobalVariables.MasterInsertIgnoreList.Contains(item.ColumnName.ToUpper()))
                    {
                        columnList.Add(new ColumnValueProperties() { DispalyMember = CommonFunctions.GetFormatedColumnName(item.ColumnName), ValueMember = item.ColumnName, DataType = item.DataType.Name.ToUpper() });
                    }
                }
                FilterWindowViewModel vmFilterWindow = new FilterWindowViewModel(columnList);
                if (vmFilterWindow != null)
                {
                    MessageService.ShowPopupWindow(vmFilterWindow);
                    if (!string.IsNullOrEmpty(vmFilterWindow.FilterString))
                    {
                        filterString = vmFilterWindow.FilterString;
                    }
                    FilteringAndSortingDatatable();
                    SetCurrentRecord(0);
                }
            }
        }

        #endregion

        #region Sort Button

        private void ExecuteSort(object sender, RoutedEventArgs e)
        {
            if (DtAllMasterData != null && DtAllMasterData.Rows.Count > 0)
            {
                sortString = String.Empty;
                ObservableCollection<ColumnValueProperties> columnList = new ObservableCollection<ColumnValueProperties>();
                foreach (DataColumn item in DtAllMasterData.Columns)
                {
                    if (!GlobalVariables.MasterInsertIgnoreList.Contains(item.ColumnName.ToUpper()))
                    {
                        columnList.Add(new ColumnValueProperties() { DispalyMember = CommonFunctions.GetFormatedColumnName(item.ColumnName), ValueMember = item.ColumnName });
                    }
                }

                object currentPrimaryKey = CurrentRow[PrimaryKeyField];

                SortWindowViewModel vmSortWindow = new SortWindowViewModel(columnList);
                if (vmSortWindow != null)
                {
                    MessageService.ShowPopupWindow(vmSortWindow);
                    if (!string.IsNullOrEmpty(vmSortWindow.SortString))
                    {
                        sortString = vmSortWindow.SortString;
                    }
                    FilteringAndSortingDatatable();
                    DtAllMasterData.PrimaryKey = new DataColumn[] { DtAllMasterData.Columns[PrimaryKeyField] };
                    CurrentIndex = DtAllMasterData.Rows.IndexOf(DtAllMasterData.Rows.Find(currentPrimaryKey));
                    SetCurrentRecord(CurrentIndex);
                }
            }
        }

        #endregion

        #region Search Button

        private void ExecuteSearch(object sender, RoutedEventArgs e)
        {
            if (DtAllMasterDataOriginal != null && DtAllMasterDataOriginal.Rows.Count > 0)
            {
                ListWindowViewModel vmListWindow = new ListWindowViewModel();
                if (vmListWindow != null)
                {
                    vmListWindow.TableName = TableName;
                    vmListWindow.FilterString = string.IsNullOrEmpty(filterString) ? "" : filterString;
                    vmListWindow.Initialize();
                    MessageService.ShowPopupWindow(vmListWindow);
                    if (vmListWindow.SelectedRow != null)
                    {
                        DtAllMasterData.PrimaryKey = new DataColumn[] { DtAllMasterData.Columns[PrimaryKeyField] };
                        CurrentIndex = DtAllMasterData.Rows.IndexOf(DtAllMasterData.Rows.Find(vmListWindow.SelectedRow[PrimaryKeyField]));
                        SetCurrentRecord(CurrentIndex);
                    }
                }
            }
        }

        #endregion

        #region Print Button

        private void ExecutePrint(object sender, RoutedEventArgs e)
        {
            List<IReportParameters> repParaList = new List<IReportParameters>();
            repParaList.Add(new ReportParameters() { ParameterIndex = 0, ParameterName = "ReportName", InputValue = Title });
            repParaList.Add(new ReportParameters() { ParameterIndex = 1, ParameterName = "CompanyName", InputValue = GlobalVariables.CompanyName });
            repParaList.Add(new ReportParameters() { ParameterIndex = 2, ParameterName = "Address", InputValue = GlobalVariables.Address });
            repParaList.Add(new ReportParameters() { ParameterIndex = 3, ParameterName = "ContactDetails", InputValue = GlobalVariables.ContactDetails });
            repParaList.Add(new ReportParameters() { ParameterIndex = 4, ParameterName = "GeneratedUser", InputValue = GlobalVariables.LoggedInUser });
            repParaList.Add(new ReportParameters() { ParameterIndex = 5, ParameterName = "GenaratedMachine", InputValue = Environment.MachineName });
            repParaList.Add(new ReportParameters() { ParameterIndex = 6, ParameterName = "CopyRight", InputValue = GlobalVariables.CopyRight });

            ReportsDocument ReportsDocument = new ReportsDocument();

            if (ReportsDocument != null)
            {
                ReportsDocument.InputValueList = repParaList;
                ReportDocument reportdoc;

                reportdoc = ReportsDocument.GetReportDocument(ReportFolder + ":" + ReportName.Trim(), DtAllMasterData); ;
                if (reportdoc != null)
                {
                    ReportViewerViewModel vmReportWindow = new ReportViewerViewModel(reportdoc, Title);
                    if (vmReportWindow != null)
                        MessageService.ShowReport(vmReportWindow);
                }
            }
        }

        #endregion

        #region Button1 Button

        private void ExecuteButton1(object sender, RoutedEventArgs e)
        {
            if (ExecuteButton1Event != null)
                ExecuteButton1Event(sender, e);
        }

        #endregion

        #region Button2 Button

        private void ExecuteButton2(object sender, RoutedEventArgs e)
        {
            if (ExecuteButton2Event != null)
                ExecuteButton2Event(sender, e);
        }

        #endregion

        #region Button3 Button

        private void ExecuteButton3(object sender, RoutedEventArgs e)
        {
            if (ExecuteButton3Event != null)
                ExecuteButton3Event(sender, e);
        }

        #endregion

        #region Button4 Button

        private void ExecuteButton4(object sender, RoutedEventArgs e)
        {
            if (ExecuteButton4Event != null)
                ExecuteButton4Event(sender, e);
        }

        #endregion

        #region Button5 Button

        private void ExecuteButton5(object sender, RoutedEventArgs e)
        {
            if (ExecuteButton5Event != null)
                ExecuteButton5Event(sender, e);
        }

        #endregion

        #region Master Tool Bar Loaded

        private void MasterToolBarLoad(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;

            IsValid = false;
            ResetDefaults(false);
            var window = Window.GetWindow(this);
            if (window != null)
            {
                window.Title = Title;
                window.KeyDown += HandleKeyPress;           //use to manage the enter key press in parent window
            }
        }

        #endregion

        #endregion



    }

}